<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Model\TempPhone;
use App\Model\User_login_info;
use App\Http\Controllers\Api\Common;

class UserController extends Controller
{
	public function json($code,$data=[])
	{
		return response()->json([
				'status' => $code,
				
				'data' => $data,

			]);
	}

   //判断用户名

   public function nameManage()
   {
   	$name = $_POST['name'];

      $user = User::select(['id','name','pass'])
         ->where('name',$name)
         ->first();

         // dd($user);
         if ($user) {

           echo 1;

           
         }else{
            echo 2;
         }    
   
   }

   //判断手机号
   
   public function phoneManage()
   {
   	$phone = $_POST['phone'];

      $userPhone = User::select(['id','name','phone'])
         ->where('phone',$phone)
         ->first();
   //判断手机号是否存在
         if ($userPhone) {

            echo 1;

         } else {

            echo 2;
         }
   }

   //判断邮箱
   
   public function emailManage()
   {
   	$email = $_POST['email'];

   	// $patten ='/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';

   	$userEmail = User::select(['id','name','email'])
         ->where('email',$email)
         ->first();
         if ($userEmail) {
            
            echo 1;

         }else{

            echo 2;
         }
   }

// 判断密码的正则
// 
   public function passManage()
   {
   	$pass = $_POST['pass'];

   	$patten = '/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,16}$/';

   		preg_match($patten,$pass,$match);
   			if($match)
   			{
   				echo 1;

   			}else{

   				echo 2;

   			}
   }
   //判断验证码是否正确
   
   public function codeManage()
   {
      $code = $_POST['code'];
      $phone =$_POST['phone'];
      $phoneCode = TempPhone::select('phone','code')
      ->where('phone',$phone)
      ->orderBy('id','desc')
      ->first();
      



      if ($code == $phoneCode->code) {

         echo 1;

      }  else {

         echo 2;
      }
   }
   // 实现注册
   
   public function handerRegister()
   {
      
   	$name = $_POST['name'];
   	$pass = $_POST['pass'];
      $email= $_POST['email'];
      $phone= $_POST['phone'];
      $code = $_POST['code'];
     
      if (!$name) {
         return $this->json(1501);
      } 
      if (!$pass) {
         return $this->json(1502);
      } 
      if (!$email) {
         return $this->json(1503);
      } 
      if (!$phone) {
         return $this->json(1504);
      }
       if (!$code) {
         return $this->json(1505);
      }

      $bool = User::insert([
            'name'=>$name,
            'pass'=>password_hash($pass,PASSWORD_DEFAULT),
            'email'=>$email,
            'phone'=>$phone,
            'code'=>$code,
            ]);
      // $code = $_POST['code'];
      // $phone =$_POST['phone'];
      $phoneCode = TempPhone::select('phone','code')
      ->where('phone',$phone)
      ->orderBy('id','desc')
      ->first();
      

      if ($code !== $phoneCode->code) {

          return $this->json(1506);

      }  

          
         if ($bool) {
            //注册成功
            return $this->json(1200);

         } else {
            //注册失败
            return $this->json(1500);

         }
      }





//======================登录功能=====================
   public function handerLogin()
   {
      $name = $_POST['name'];
      $pass = $_POST['pass'];
      $code = $_POST['code'];

      //判断验证码是否正确
      // if ($code != session()->get('code')) {
      //     return $this->json(1700);
      // }

      if (!$name) {

         return $this->json(1501);

      }

      if (!$pass) {

         return $this->json(1502);

      }

      $user = User::select(['id','name','pass'])->where('name',$name)->first();

      if (!$user) {
      //用户不存在
      return $this->json(1404);
      } else {
      // 把用户数据存进session
      session()->put('user',$name);
      }

      //检查用户最近30分钟密码错误次数
      $res = $this->checkPassWrongTime($user['id']);
      // dd($res);
      //错误次数超过限制次数
      if ( $res === false ) {
         return $this->json(1800);
         exit;
      }
      //验证密码
      if(password_verify($pass,$user->pass)) {
         return $this->json(1200);

      } else {
         //记录密码错误次数
      $this->recordPassWrongTime($user['id']);

         return $this->json(1402);
         exit;
         
      }
      
   }

   //记录密码输出信息
   protected function recordPassWrongTime($uid)
   {
      //ip2long()函数将IP地址转换成数字
      $ip = ($_SERVER['REMOTE_ADDR']);
      $time = date('Y-m-d H:i:s');
      $sql = User_login_info::insert([
            'uid'=>$uid,
            'ipaddr'=>$ip,
            'logintime'=>$time,
            'pass_wrong_time_status'=>2,

         ]);
   }

   /**
     * 检查用户最近$min分钟密码错误次数
     * $uid 用户ID
     * $min  锁定时间
     * $wTIme 错误次数
     * @return 错误次数超过返回false,其他返回错误次数，提示用户
     */
   protected function checkPassWrongTime($uid,$min=1, $wTIme=3)
   {

     if ( empty($uid) ) {

         throw new \Exception("第一个参数不能为空");
     }

     $time = time();
     $prevTime = time() - $min*60;
     $finalTime = date('Y-m-d H:i:s', $time);
     $finalPrevTime = date('Y-m-d H:i:s', $prevTime);
     //用户所在登录ip
   //        $ip = intval($_SERVER['REMOTE_ADDR']);
     $ip = ($_SERVER['REMOTE_ADDR']);
     //pass_wrong_time_status代表用户输出了密码
     // $sql = "select * from user_login_info where uid={$uid} and pass_wrong_time_status=2 and logintime between $prevTime and $time and ipaddr=$ip";
     // dd($prevTime,$time);
     // dd(date('Y-m-d H:i:s', $prevTime));
     // dd($finalPrevTime);
     $utime = User_login_info::select('uid','pass_wrong_time_status','ipaddr')
         ->where([
             ['uid',$uid],
             ['pass_wrong_time_status',2],
             ['ipaddr',$ip]
         ])
         ->whereBetween('logintime',[$finalPrevTime,$finalTime])
         ->count();
     //统计错误次数
     
     // var_dump($wrongTime);
     //判断错误次数是否超过限制次数
     if ( $utime >= $wTIme ) {

         return false;
     }

     return $utime;
   }
   public function __call($methodName, $params)
   {

        echo '访问的页面不存在','<a href="./login.php">返回登录页</a>';
   }

   public function logout() 
   {
      session()->flush();
      return redirect('/login');
   }

}
